const app = getApp()
const WebSocket = require('../../utils/WebSocket.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    QRCode: '',
    SendClientId: '',  // 小程序和后端的WebSocket的ID
    ReceiveID: '',     // 需要件将消息发送给谁
  },
  /**
   * 页面加载
   */
  onLoad: function (option) {
    var that = this;
    if (!!option.scene) {
      this.setData({
        //获取二维码中的参数
        QRCode: option.scene,
        SendClientId: option.scene.substring(0, 25),
        ReceiveID: option.scene.substring(7)
      });

      // 创建连接
      WebSocket.connectSocket({ ClientID: option.scene.substring(0, 25), ReceiveID: option.scene.substring(7) });
      // 设置接收消息回调
      WebSocket.onSocketMessageCallback = this.onSocketMessageCallback;
      setTimeout(() => {
        that.sendSocketMessage("Scan", 0);
      }, 100);

    }
  },
  /**
   * 发送消息
   */
  sendSocketMessage(Action, Message) {
    console.log("调用发送消息");
    var ReceiveID = this.data.ReceiveID;
    WebSocket.sendSocketMessage({ "SendClientId": "", "Action": Action, "Msg": Message, "ReceiveID": ReceiveID });

  },
  // Socket收到的信息
  onSocketMessageCallback: function (res) {
    console.log(res);
  },
  // 页面销毁时关闭连接
  onUnload: function (options) {
    WebSocket.closeSocket();
  },
  /**
   * 获取用户信息
   */
  getUserProfile(info) {
    var that = this;
    wx.showLoading({
      title: '正在登录...',
      mask: true,
    })
    // 执行登录操作
    let code = '';
    wx.login({
      success: (res) => {
        code = res.code;
      },
    });
    // 获取用户信息
    wx.getUserProfile({
      lang: 'zh_CN',
      desc: '用户登录',
      success: (res) => {
        that.getSessionKey(res.rawData, code);
      },
      fail: () => {
        that.closeLogin();
        // 失败回调
        wx.hideLoading();
      }
    });
  },
  /**
   * 获取SessionKey
   */
  getSessionKey: function (userInfo, code) {
    var that = this
    that.GetOpenId(userInfo, code);
  },
  /**
   * 获取openId，并保存用户
   */
  GetOpenId: function (userInfo, code) {
    //获取openId
    var that = this
    //开始请求用户Sessionkey
    wx.request({
      url: app.globalData.baseWechatUrl + '/WechatUserProxy',
      data: {
        userInfo: userInfo,
        code: code,
        F_DeviceID: wx.getStorageSync("RegisterID")
      },
      dataType: "json",
      method: "POST",
      success: function (res) {
        wx.hideLoading(); //隐藏加载中提示
        var data = res.data;
        if (data.statusCode == 200) {
          var tempData = JSON.parse(userInfo);
          tempData.openId = data.data.data.openId;
          that.sendSocketMessage("Login", JSON.stringify(tempData));
        } else {
          wx.showToast({
            title: "登录失败",
            duration: 1000,
            icon: 'none',
            mask: true
          })
        }
      }
    })
  },
  //取消登录
  CancelLoginBtn: function () {
    this.sendSocketMessage("Calcel", "2");
    wx.showToast({
      title: "取消登录",
      duration: 1000,
      icon: 'none',
      mask: true
    })
  },
})

